package com.zeng.user.repository;

import com.zeng.user.domain.User;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author ahaschool
 * @date 2021-03-03 10:57
 */

public class JdbcUserRepository implements UserRepository {

    private final Logger logger = Logger.getLogger(JdbcUserRepository.class.getName());

    private static class Sql {
        public static final String INSERT_USER_DML_SQL =
                "INSERT INTO users(name,password,email,phoneNumber) VALUES " +
                        "(?,?,?,?)";
        public static final String QUERY_USERS_DML_SQL = "SELECT id,name,password,email,phoneNumber FROM users where email=?";

        public static final String CREATE_USERS_TABLE_DDL_SQL = "CREATE TABLE users(" +
                "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
                "name VARCHAR(16) DEFAULT '', " +
                "password VARCHAR(64) NOT NULL, " +
                "email VARCHAR(64) NOT NULL, " +
                "phoneNumber VARCHAR(64) DEFAULT ''" +
                ")";
    }

    @Resource(name = "jdbc/UserPlatformDB")
    private DataSource dataSource;

    @PostConstruct
    public void init() {
        ifNotExistCreateTable();
    }


    @Override
    public void saveUser(User user) {
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(Sql.INSERT_USER_DML_SQL);
            preparedStatement.setString(1, user.getName());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setString(3, user.getEmail());
            preparedStatement.setString(4, user.getPhoneNumber());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("sql插入异常", e);
        }
    }

    @Override
    public User findByEmail(String email) {
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(Sql.QUERY_USERS_DML_SQL);
            preparedStatement.setString(1, email);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (!resultSet.next()) {
                return null;
            }
            User user = new User();
            user.setId(resultSet.getLong("id"));
            user.setEmail(resultSet.getString("email"));
            user.setPassword(resultSet.getString("password"));
            user.setPhoneNumber(resultSet.getString("phoneNumber"));
            return user;
        } catch (SQLException e) {
            throw new RuntimeException("查询错误！", e);
        }
    }

    public void destroy() {
        logger.log(Level.INFO, "destroy method completed!");

    }

    private void ifNotExistCreateTable() {
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet res = metaData.getTables(null, null, null, new String[]{"TABLE"});
            Set<String> set = new HashSet<>();
            while (res.next()) {
                set.add(res.getString("TABLE_NAME"));
            }
            String usersTableName = "USERS";
            if (!set.contains(usersTableName)) {
                Statement statement = connection.createStatement();
                statement.executeUpdate(Sql.CREATE_USERS_TABLE_DDL_SQL);
            }
        } catch (SQLException e) {
            throw new RuntimeException("初始化表失败", e);
        }
        logger.log(Level.INFO, "表初始化完成！");
    }

}
